const path = require('path')
const { VueLoaderPlugin } = require('vue-loader')
const HTMLWebpackPlugin = require('html-webpack-plugin')
const { DefinePlugin } = require('webpack')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

const isDev = process.env.NODE_ENV === 'development'

const styleRule = isDev ? 'style-loader' : MiniCssExtractPlugin.loader

module.exports = {
  entry: './src/main.js',
  output: {
    filename: '[name].[contenthash:7].js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        use: 'vue-loader',
      },
      {
        test: /\.(js|ts)$/,
        use: 'babel-loader',
      },
      {
        test: /\.(css|less|scss|sass)$/,
        use: [styleRule, 'css-loader', 'less-loader'],
      },
      {
        test: /\.(jpe?g|png|gif)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 1024 * 8,
              esModule: false,
            },
          },
        ],
      },
    ],
  },
  plugins: [
    new VueLoaderPlugin(),
    new HTMLWebpackPlugin({
      template: './public/index.html',
      title: 'Hello World',
      filename: 'index.html',
      inject: 'body',
      hash: true,
    }),
    new DefinePlugin({
      BASE_URL: '/public/',
    }),
    new CleanWebpackPlugin(),
    new MiniCssExtractPlugin({
      filename: isDev ? 'style/[name].css' : 'style/[name].[contenthash:7].css',
    }),
    new FriendlyErrorsWebpackPlugin({
      additionalTransformers: [transformer],
      additionalFormatters: [formatter],
    }),
  ],
}
